/*
 * Copyright 2006 JTech Network, Sweden
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package se.jtech.xml;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.namespace.NamespaceContext;

/**
 * A simple <code>NamespaceContext</code> that can be configured using a
 * <code>Map</code> of prefixes and URIs.
 * 
 * The method {#getPrefixes} is not implemented.
 * 
 * @author Claes Buckwalter (claes@jtech.se)
 */
public class ConfigurableNamespaceContext implements NamespaceContext {

    final Map uri2Prefix;

    final Map prefix2Uri;

    /**
     * Creates a new context for resolving namespace URIs and prefixes
     * 
     * @param namespaces
     *            A Map with prefixes as keys and namespace URIs values. All
     *            keys and values must be Strings.
     * @throws IllegalArgumentException
     *             if Map of namespaces is null
     */
    public ConfigurableNamespaceContext(Map namespaces) {
        if (namespaces == null) {
            throw new IllegalArgumentException(
                    "Namespaces Map may not be null.");
        }
        // Map prefixes to URIs
        prefix2Uri = namespaces;
        // Map URIs to prefixes
        uri2Prefix = new HashMap();
        final Iterator keys = prefix2Uri.keySet().iterator();
        while (keys.hasNext()) {
            final Object key = keys.next();
            uri2Prefix.put(prefix2Uri.get(key), key);
        }
    }

    public ConfigurableNamespaceContext() {
        this(new HashMap());
    }

    public void addNamespace(String uri, String prefix) {
        uri2Prefix.put(uri, prefix);
        prefix2Uri.put(prefix, uri);
    }

    public String getNamespaceURI(String prefix) {
        if (prefix == null) {
            throw new IllegalArgumentException("Prefix may not be null.");
        }
        String uri = (String) prefix2Uri.get(prefix);
        return uri;
    }

    public String getPrefix(String uri) {
        if (uri == null) {
            throw new IllegalArgumentException("Namespace URI may not be null.");
        }
        String prefix = (String) uri2Prefix.get(uri);
        return prefix;
    }

    public Iterator getPrefixes(String uri) {
        return prefix2Uri.keySet().iterator();
    }

}
